axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
const tb = document.querySelector('#tb')
// 获取图书列表
const getBooksList = () => {
  axios({
    url: '/api/getbooks',
    method: 'GET'
  }).then(({ data: res }) => {
    const { data } = res
    tb.innerHTML = data.map(item => {
      return `
      <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>
      `
    }).join('')
  })
}

const bookForm = document.querySelector('#bookForm')

bookForm.addEventListener('submit', function (e) {
  e.preventDefault()
  const data = serialize(this, { hash: true })
  // 添加图书
  if (e.submitter.dataset.id === '1') {
    axios({
      url: '/api/addbook',
      method: 'POST',
      data
    }).then(({ data: res }) => {
      const { msg, status } = res
      if (status !== 201) return alert('添加失败')
      alert(msg)
      getBooksList()
    })
  }

  if (e.submitter.dataset.id === '2') {
    axios({
      url: '/api/getbooks',
      method: 'GET',
      params: data
    }).then(({ data: res }) => {
      const { data } = res
      tb.innerHTML = data.map(item => {
        return `
        <tr>
        <td>${item.id}</td>
        <td>${item.bookname}</td>
        <td>${item.author}</td>
        <td>${item.publisher}</td>
        <td><a href="#" data-id="${item.id}">删除</a></td>
      </tr>
        `
      }).join('')
    })
  }
})


// 删除图书
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    axios({
      method: 'GET',
      url: '/api/delbook',
      params: {
        id: Number(e.target.dataset.id)
      }
    }).then(({ data: res }) => {
      const { msg } = res
      alert(msg)
      getBooksList()
    })
  }
})


getBooksList()